//
//  CZEmoticonCollectionViewCell.swift
//  Blog
//
//  Created by whitcast on 16/7/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// 表情视图cell
class CZEmoticonCollectionViewCell: UICollectionViewCell {
    // 存储20个表情按钮
    private lazy var emoticonButtons: [UIButton] = [UIButton]()
    // 绑定数据模型
    var emoticons: [CZEmoticon]? {
        didSet {
            guard let ets = emoticons else {
                return
            }
            for value in emoticonButtons {
                value.hidden = true
            }
            
            for (i, value) in ets.enumerate() {
                // 获取表情按钮
                let button = emoticonButtons[i]
                
                // 设置数据显示按钮
                button.hidden = false
                
                if value.type == "0" {
                    // 设置图片
                    button.setImage(UIImage(named: value.path!), forState: .Normal)
                    button.setTitle(nil, forState: .Normal)
                } else {
                    // 设置emoji
                    button.setTitle((value.code! as NSString).emoji(), forState: .Normal)
                }
            }
        }
    }
    
    var indexPath: NSIndexPath? {
        didSet{
            guard let index = indexPath else {
                return
            }
            messageLabel.text = "当前滚动到第\(index.section+1)组第\(index.item+1)行"

        }
    }
    
    // MARK: -- 懒加载
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.redColor(), fontSize: 30)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 绑定数据模型
    private func setupUI() {
//        contentView.addSubview(messageLabel)
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView)
//        }
        addChildButton()
    }
    
    // 添加20个表情按钮的方法
    private func addChildButton() {
        // 循环遍历20此
        for _ in 0..<20 {
            let button = UIButton()
            contentView.addSubview(button)
            emoticonButtons.append(button)
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        //  计算宽度
        let itemWidth = width / 7
        //  计算高度
        let itemHeight = height / 3
        
        
        for (i, button) in emoticonButtons.enumerate() {
            //  计算列的索引
            let colIndex = i % 7
            
            //  计算行的索引
            let rowIndex = i / 7
            //  设置大小
            button.size = CGSize(width: itemWidth, height: itemHeight)
            //  设置x坐标
            button.x = CGFloat(colIndex) * itemWidth
            //  设置y坐标
            button.y = CGFloat(rowIndex) * itemHeight

        }
    
    }
}
